<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Importw extends CI_Controller {

	var $per_page;
	var $is_view;
	var $is_edit;

	public function __construct()
	{
		parent::__construct();	

		$logged_in = $this->session->userdata('logged_in');
		if($logged_in)
		{
		   $session_data = $this->session->userdata('logged_in');
		   $data['username'] = $session_data['username'];		   
		}
		else
		{
	     //If no session, redirect to login page
	     redirect('login', 'refresh');
   		}   		

   		/////////////////// Previleage section ///////////////////////////////////
   		// retrieve information
   		// load model
   		$this->load->model('User_model');
   		$userInfo = $this->User_model->userInfo($data['username']);   		   			

   		if(empty($userInfo))
   		{
   			redirect('login', 'refresh');
   		}
   		else
   		{
   			// check previleage
   			$this->is_edit = $userInfo->is_edit;
   			$this->is_view = $userInfo->is_view;   			
   		}   		

   		//// check if user is affiliate, redirect to affliate section ////////////
   		$is_affiliate = $userInfo->user_cat;

   		if(!empty($is_affiliate) && ($is_affiliate == 2))
   		{
   			redirect('affiliate');
   		}

   		//////////////////////////////////////////////////////////////////////////   

   		// get controller request
   		$controller_call = $this->uri->segment(1);
   		$action_call = $this->uri->segment(2);

   		$full_call = $controller_call . '/' . $action_call;

   		$list_view_pages = array('importw/history');
   		$list_edit_pages = array('importw/index');

   		if(in_array($full_call, $list_view_pages))
   		{
   			if(!$this->is_view)
   				redirect('privileage/error');
   		}
   		else if(in_array($full_call, $list_edit_pages))
   		{
   			if(!$this->is_edit)
   				redirect('privileage/error');
   		}
   		else if($controller_call == 'importw')	// special action
   		{
   			if(!$this->is_edit)
   				redirect('privileage/error');
   		}

   		////////////////////////////////////////////////////////////////////////////

		// gán giá trị tiêu đề form
		$this->template->set('nav',$this->uri->segment(1));
		$this->template->set('title', 'Nhập kho');
		$this->template->set('section', 'Nhập kho');	

		// load model kho
		$this->load->model('Storage_model');	
		// load model history kho
		$this->load->model('Storage_product_history_model');
		// load products that in storage
		$this->load->model('Storage_product_model');
		// load product size
		$this->load->model('Product_sizes_model');
		// load product model
		$this->load->model('Product_model');	

		// define per_page
		$this->per_page = 10;	
	}

	// index 
	// list all storage with empty space available
	public function index()
	{
		$storage = $this->input->post('storage');
		$quantity = $this->input->post('quantity');

		if(!empty($storage))
			$data['storage']= $storage;
		if(!empty($quantity))
			$data['quantity'] = $quantity;

		$cond = array();

		if(!empty($storage))		
			$cond['storage'] = $storage;
		if(!empty($squantity))
			$cond['quantity']= $quantity;
		// all storage
		$data['allStorage'] = $this->Storage_model->loadAll($cond);		
		// all history
		$data['allImportHistory'] = $this->Storage_product_history_model->loadAll();

		$this->template->load('admin/template','admin/importw',$data);
	}	

	public function process($storage_id = false)
	{
		// store storage_id
		$data['storage_id'] = $storage_id;

		// lay thong tin kho
		$data['storage'] = $this->Storage_model->getEntry($storage_id);

		// get data of import items
		$data['dataImport'] = $this->Storage_product_model->getEntry('storage_id',$storage_id);		

		// 		
		$tmp_array = array();

		foreach ($data['dataImport'] as $row) 
		{
			$storage = $this->Storage_model->getEntry($row->storage_id);
			$product = $this->Product_model->getEntry($row->product_id);
			$product_sizes = $this->Product_sizes_model->getEntry('code',$row->product_code);

			$tmp_array[] = array(
					'storage_product_id'	=>	$row->id,
					'product'				=> $product->title,
					'color'					=> $product->color,
					'size'					=> $product_sizes->size,
					'code'					=> $row->product_code,
					'created_date'			=> $row->created_date,
				);	
		}

		$data['dataImport'] = $tmp_array;

		//

		$this->template->load('admin/template','admin/importw_form',$data);
	}

	// add item to storage
	public function add($storage_id)
	{
		// get code
		$code = $this->input->post('code');

		if(empty($code))
		{
			redirect('importw/process/'.$storage_id);
		}		

		// check available of code
		$product_size = $this->Product_sizes_model->getEntry('code',$code);
		$product = $this->Product_model->getEntry($product_size->product_id);

		if(empty($product_size))
		{
			redirect('importw/process/'.$storage_id);
		}

		// check left quantity of storage
		$storage = $this->Storage_model->getEntry($storage_id);
		$left_quantity = $storage->left_quantity;

		if($left_quantity == 0)
		{
			redirect('importw/process/'.$storage_id);
		}
		// Update left quantity of product
		$this->Storage_model->updateQuantity($storage_id,'decrease');

		// OK, insert code		
		$data = array(
				'storage_id'	=>	$storage_id,
				'product_id'	=>	$product_size->product_id,
				'product_code'	=>	$product_size->code,
				'active'		=>	1,
			);
		$insert_id = $this->Storage_product_model->insertEntry($data);		

		// insert quantity to product_sizes
		$this->Product_sizes_model->updateQuantity($code, 'increase');

		// logged history
		$data = array(
				'product'		=>	$product->title,
				'product_id'	=>	$product->id,
				'size'			=>	$product_size->size,
				'code'			=>	$code,
				'storage_id'	=>	$storage_id,
				'storage'		=>	$storage->title,
				'type'			=>	1,				
			);
		$this->Storage_product_history_model->insertHistory($data);

		redirect('importw/process/'.$storage_id);
	}

	// delete code from storage
	public function remove($storage_id,$code,$id)
	{
		// get code		
		if(empty($id))
		{
			redirect('importw/process/'.$storage_id);
		}

		// remove record with id
		$this->Storage_product_model->remove($id);	

		// Remove quantity to product_sizes
		$this->Product_sizes_model->updateQuantity($code,'decrease');			

		// increase quantity 
		$this->Storage_model->updateQuantity($storage_id,'increase');
		
		redirect('importw/process/'.$storage_id);
	}

	public function info($storage_id = false)
	{		
		// store storage_id
		$data['storage_id'] = $storage_id;

		// lay thong tin kho
		$data['storage'] = $this->Storage_model->getEntry($storage_id);

		// get all logs of importing
		$data['historyImport'] = $this->Storage_product_history_model->getEntry('storage_id',$storage_id);		
	}

	public function history($start = false)
	{		
		$search = $this->input->get('search',true);

		$warning = $this->session->userdata('warning');

		if(!empty($warning))
		{
			$data['warning'] = $warning;
			$this->session->unset_userdata('warning');
		}
		if(!empty($search))		
		{
			$search = date('Y-m-d',strtotime($search));
			$data['search'] = $search;
			$this->session->set_userdata('search', $data['search']);
		}

		$session_search = $this->session->userdata('search');

		if(!empty($session_search))
		{
			$data['search'] = $session_search;
		}

		if(empty($start))
			$start = 1;

		$start = ($start - 1) * $this->per_page;
		$limit = $this->per_page;

		// history: type=1 import type=2 export
		$return = $this->Storage_product_history_model->loadHistoryV2(1,$search,$limit,$start);

		$data['history'] = $return['data'];
		$total_history = $return['count'];
		$data['total'] = $total_history;

		////////////////// pagination //////////////////////////////////////
		$this->load->library('pagination');

		$config['base_url'] = site_url('importw/history/');
		$config['total_rows'] = $total_history;
		$config['per_page'] = $this->per_page;
		$config['uri_segment'] = 3;
		$config['use_page_numbers'] = TRUE;
		$config['full_tag_open'] = '<ul class="pagination">';
		$config['full_tag_close'] = '</ul>';
		// first link
		$config['first_link'] = '&laquo;';
		$config['first_tag_open'] = '<li>';
		$config['first_tag_close'] = '</li>';
		// next link
		$config['next_tag_open'] = '<li>';
		$config['next_tag_close'] = '</li>';	
		// previous link
		$config['prev_tag_open'] = '<li>';
		$config['prev_tag_close'] = '</li>';
		// end link
		$config['last_link'] = '&raquo;';
		$config['last_tag_open'] = '<li>';
		$config['last_tag_close'] = '</li>';
		// current
		$config['cur_tag_open'] = '<li class="active"><a href="#">';
		$config['cur_tag_close'] = '<span class="sr-only">(current)</span></a></li>';
		// digit link
		$config['num_tag_open'] = '<li>';
		$config['num_tag_close'] = '</li>';

		$this->pagination->initialize($config); 

		$data['paging_history'] = $this->pagination->create_links();

		////////////////////////////////////////////////////////////////////

		$this->template->load('admin/template','admin/importw_history',$data);
	}

	// print excel
	function printExcel()
	{
		$date = $this->input->get('date',true);

		if(!empty($date))
		{
			$date = date('Y-m-d',strtotime($date));
		}

		// history: type=1 import type=2 export
		$data['history'] = $this->Storage_product_history_model->loadHistory(1,$date);

		if(empty($data['history']))		
		{
			$this->session->set_userdata('warning','Dữ liệu trống');
			redirect('importw/history');
		}

		////////////////////////////////////////////////////////////////
		//load our new PHPExcel library
		$this->load->library('excel');
		//activate worksheet number 1
		$this->excel->setActiveSheetIndex(0);
		//name the worksheet
		$this->excel->getActiveSheet()->setTitle('test worksheet');
		//set cell A1 content with some text
		$this->excel->getActiveSheet()->setCellValue('A1', 'STT');		
		$this->excel->getActiveSheet()->setCellValue('B1', 'Sản phẩm');
		$this->excel->getActiveSheet()->setCellValue('C1', 'Size áo');
		$this->excel->getActiveSheet()->setCellValue('D1', 'Mã áo');
		$this->excel->getActiveSheet()->setCellValue('E1', 'Kho');
		$this->excel->getActiveSheet()->setCellValue('F1', 'Ngày tạo');		

		$i = 2;
		$j = 1;
		$today = date('YmdHis',strtotime('now'));

		foreach ($data['history'] as $row) 
		{
			$this->excel->getActiveSheet()->setCellValue('A'.$i, $j);			
			$this->excel->getActiveSheet()->setCellValue('B'.$i, $row->product);
			$this->excel->getActiveSheet()->setCellValue('C'.$i, $row->size);
			$this->excel->getActiveSheet()->setCellValue('D'.$i, $row->code);			
			$this->excel->getActiveSheet()->setCellValue('E'.$i, $row->storage);			
			$this->excel->getActiveSheet()->setCellValue('F'.$i, $row->date_created);			

			$j++;
			$i++;
		}
		
		//change the font size
		//$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setSize(20);
		//make the font become bold
		//$this->excel->getActiveSheet()->getStyle('A1')->getFont()->setBold(true);
		//merge cell A1 until D1
		//$this->excel->getActiveSheet()->mergeCells('A1:D1');
		//set aligment to center for that merged cell (A1 to D1)
		$this->excel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
				 
		$filename='nhap_kho_'.$today.'.xls'; //save our workbook as this file name
		header('Content-Type: application/vnd.ms-excel'); //mime type
		header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
		header('Cache-Control: max-age=0'); //no cache
				             
		//save it to Excel5 format (excel 2003 .XLS file), change this to 'Excel2007' (and adjust the filename extension, also the header mime type)
		//if you want to save it as .XLSX Excel 2007 format
		$objWriter = PHPExcel_IOFactory::createWriter($this->excel, 'Excel5');  
		//force user to download the Excel file without writing it to server's HD
		$objWriter->save('php://output');	
	}	

	//////////// add warning to code /////////////////////////////////////
	// public function showWarning($level, $text)
	// {
	// 	switch ($level) {
	// 		case 'value':
	// 			# code...
	// 			break;
			
	// 		default:
	// 			# code...
	// 			break;
	// 	}
	// }

}
